package com.dg.gaming.server;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

import com.dg.gaming.server.messages.*;
import org.xsocket.*;
import org.xsocket.connection.*;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2009</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class ServerConnectionHandler implements IDataHandler,
        IDisconnectHandler, IConnectHandler {

    private WorkerQueue wq = null;

    public ServerConnectionHandler(WorkerQueue wq) {

        this.wq = wq;
    }

    public boolean onDisconnect(INonBlockingConnection nbc) throws
            IOException {
        byte[] bytes = new byte[0];
        wq.addMessage(new DisconnectMessage(nbc, bytes));
        return true;
    }

    public boolean onData(INonBlockingConnection nbc) throws
            BufferUnderflowException, IOException, ClosedChannelException,
            MaxReadSizeExceededException {

        byte[] bytes = nbc.readBytesByLength(nbc.available());
//        System.out.println(bytes.length);

        wq.addMessage(new UserMessage(nbc, bytes));

        return true;
    }

    public boolean onConnect(INonBlockingConnection nbc) throws
            BufferUnderflowException, IOException, MaxReadSizeExceededException {
        nbc.setAutoflush(false);
//        nbc.setObject("MyObject");
//        System.out.println(nbc.getClass() + "" + nbc.getObject());
        return false;
    }


}
